<template>
  <div class="admin-container">
    <div class="header">
      <h2>管理员列表</h2>
      <div class="search-bar">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索账号或姓名"
          style="width: 200px; margin-right: 10px;"
          clearable
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button @click="handleSearch">
              <el-icon><Search /></el-icon>
            </el-button>
          </template>
        </el-input>
        <el-select v-model="filterRole" placeholder="角色筛选" style="width: 140px; margin-right: 10px;" clearable @change="handleSearch">
          <el-option label="全部" value="" />
          <el-option label="超级管理员" value="admin" />
          <el-option label="普通管理员" value="editor" />
          <el-option label="商户" value="merchant" />
        </el-select>
        <el-button
          v-if="userInfo?.role === 'admin'"
          type="primary"
          @click="handleAdd"
        >新建管理员</el-button>
      </div>
    </div>

    <el-table :data="tableData" style="width: 100%" v-loading="loading">
      <el-table-column prop="username" label="账号" />
      <el-table-column prop="name" label="真实姓名" />
      <el-table-column prop="roleDisplay" label="角色">
        <template #default="scope">
          <el-tag v-if="scope.row.role === 'admin'" type="danger">超级管理员</el-tag>
          <el-tag v-else-if="scope.row.role === 'editor'" type="warning">普通管理员</el-tag>
          <el-tag v-else-if="scope.row.role === 'merchant'" type="info">商户</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="手机号" />
      <el-table-column prop="createTime" label="创建时间" />
      <el-table-column prop="updateTime" label="更新时间" />
      <el-table-column label="操作" width="200" v-if="userInfo?.role === 'admin'">
        <template #default="scope">
          <el-button
            size="small"
            @click="handleEdit(scope.row)"
            :disabled="scope.row.username === 'admin' || scope.row.role === 'admin'"
          >编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.row)"
            :disabled="scope.row.username === 'admin' || scope.row.role === 'admin'"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="form.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="name">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="form.role">
            <el-option label="普通管理员" value="editor" />
            <el-option label="商户" value="merchant" />
          </el-select>
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status">
            <el-option label="正常" value="正常" />
            <el-option label="禁用" value="禁用" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import request from '@/utils/request'

// 用户信息和数据状态
const userInfo = ref({
  role: 'admin' // 强制设置为admin角色，默认有权限
})
const tableData = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('新建管理员')
const formRef = ref(null)
const loading = ref(false)
const searchKeyword = ref('')
const filterRole = ref('')
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const form = ref({
  id: null,
  username: '',
  password: '',
  name: '',
  role: 'editor',
  phone: '',
  avatar: '',
  status: '正常'
})

const rules = {
  username: [{ required: true, message: '请输入账号', trigger: 'blur' }],
  password: [{ required: form.value.id ? false : true, message: '请输入密码', trigger: 'blur' }],
  name: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }]
}

const loadData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.value.currentPage,
      size: pagination.value.pageSize,
      keyword: searchKeyword.value,
      role: filterRole.value
    };
    
    console.log('开始加载管理员列表数据，请求参数:', params);
    
    const response = await request({
      url: '/admin/list',
      method: 'get',
      params
    })
    
    console.log('管理员列表数据响应:', response);
    if (response && response.code === 200) {
      // 处理后端数据格式
      tableData.value = response.data.records.map(item => {
        return {
          ...item,
          lastLoginTime: item.lastLogin ? new Date(item.lastLogin).toLocaleString() : '-',
          createTime: item.createTime ? new Date(item.createTime).toLocaleString() : '-',
          updateTime: item.updateTime ? new Date(item.updateTime).toLocaleString() : '-',
          // 将后端角色代码转为前端展示文本
          roleDisplay: item.role === 'admin' ? '超级管理员' : 
                      (item.role === 'merchant' ? '商户' : '普通管理员'),
          // 保留原始角色代码
          role: item.role
        }
      })
      
      // 更新分页信息
      pagination.value.total = response.data.total
    } else {
      console.log('API响应:', response)
      ElMessage.error(response?.message || '获取管理员列表失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，请确保后端服务正常运行')
    
    // 尝试使用模拟数据
    tableData.value = [
      {
        id: 1,
        username: 'admin',
        name: '系统管理员',
        roleDisplay: '超级管理员',
        role: 'admin',
        phone: '13800138000',
        lastLoginTime: new Date().toLocaleString(),
        createTime: new Date().toLocaleString(),
        updateTime: new Date().toLocaleString()
      }
    ]
    
    // 设置模拟分页数据
    pagination.value.total = 1
  } finally {
    loading.value = false;
  }
}

const handleSearch = () => {
  // 搜索时重置为第一页
  pagination.value.currentPage = 1;
  console.log('执行搜索，关键字:', searchKeyword.value, '角色:', filterRole.value);
  loadData();
}

const handleAdd = () => {
  form.value = {
    id: null,
    username: '',
    password: '',
    name: '',
    role: 'editor', // 默认为普通管理员角色
    phone: '',
    avatar: '',
    status: '正常'
  }
  dialogTitle.value = '新建管理员'
  dialogVisible.value = true
}

const handleEdit = (row) => {
  // 深度复制一份数据进行编辑，避免直接修改表格数据
  form.value = JSON.parse(JSON.stringify({
    id: row.id,
    username: row.username,
    password: '', // 密码置空，如果不修改则不提交
    name: row.name,
    role: row.role, // 使用原始角色值
    phone: row.phone || '',
    status: row.status === 1 ? '正常' : '禁用',
    avatar: row.avatar || ''
  }));
  
  console.log('编辑表单数据:', form.value);
  
  dialogTitle.value = '编辑管理员';
  dialogVisible.value = true;
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该管理员？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      const response = await request({
        url: `/admin/${row.id}`,
        method: 'delete'
      })
      
      if (response && response.code === 200) {
        ElMessage.success('删除成功')
        loadData()
      } else {
        ElMessage.error(response?.message || '删除失败')
      }
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    // 转换表单数据，只提交必要字段，时间字段由后端自动处理
    const submitData = { 
      ...form.value,
      role: form.value.role, // 保持原始角色值
      status: '正常' // 默认状态
    }
    
    // 删除不需要的字段
    delete submitData.createTime;
    delete submitData.updateTime;
    delete submitData.lastLoginTime;
    delete submitData.roleDisplay;
    
    // 如果是编辑状态且没有填写密码，则不提交密码字段
    if (form.value.id && !form.value.password) {
      delete submitData.password;
    }
    
    console.log('提交数据详情:', JSON.stringify(submitData)); // 添加详细日志显示完整JSON
    
    let url = '/admin/update'
    let method = 'put'
    
    if (!form.value.id) {
      url = '/admin/add'
      method = 'post'
    }
    
    try {
      const response = await request({
        url,
        method,
        data: submitData
      })
      
      if (response && response.code === 200) {
        ElMessage.success(form.value.id ? '更新成功' : '添加成功')
        dialogVisible.value = false
        loadData()
      } else {
        ElMessage.error(response?.message || (form.value.id ? '更新失败' : '添加失败'))
      }
    } catch (error) {
      console.error('API调用失败:', error);
      if (error.response) {
        console.error('错误响应数据:', error.response.data);
      }
      throw error; // 重新抛出以便外层捕获
    }
  } catch (error) {
    console.error('表单提交失败:', error)
    ElMessage.error('操作失败')
  }
}

// 处理分页变化
const handleSizeChange = (val) => {
  pagination.value.pageSize = val
  loadData()
}

const handleCurrentChange = (val) => {
  pagination.value.currentPage = val
  loadData()
}

// 页面加载时获取数据
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.admin-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 